import request from '@/utils/request'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { AppVersion } from '@/framework/constant/Common'

export default class BaseRV2Api {
  constructor(module) {
    this.module = module
    this.request = request
  }

  absUrl(url = '') {
    if (url && !url.startsWith('/')) {
      url = '/' + url
    }
    return '/api/' + this.module + url
  }

  // 详情接口方法
  detail(id) {
    return this.get('detail', { id })
  }

  post(urlName, data) {
    return request.post(this.absUrl(urlName), data)
  }
  postSelf(urlName, data) {
    return request.post(urlName, data)
  }

  get(urlName, params) {
    return request.get(this.absUrl(urlName), { params })
  }
  getSelf(urlName, params) {
    return request.get(urlName, { params })
  }
  postGet(urlName, data) {
    return request.post(this.absUrl(urlName), data)
  }
  list(params) {
    const getParams = { ...params }
    Object.keys(getParams).forEach(key => {
      if (Array.isArray(getParams[key])) {
        getParams[key] = getParams[key].join(',')
      }
    })
    return this.get('list-page', getParams)
  }

  export({ filter }) {
    // return this.post('export', {
    //   exportOption,
    //   qry: filter
    // })
    axios({
      url: this.absUrl('export'),
      method: 'post',
      data: filter,
      responseType: 'blob',
      headers: {
        token: getToken(),
        Authorization: getToken(),
        AppVersion: AppVersion
      }
    }).then((response) => {
      const contentDisposition = response.headers['content-disposition']
      let fileName = ''
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
        if (fileNameMatch != null) {
          fileName = fileNameMatch[1].replace(/['"]/g, '')
          fileName = decodeURI(fileName)
        }
      }
      const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }) // 假设是.xlsx文件
      const url = window.URL.createObjectURL(blob)
      // 创建隐藏的a标签
      const link = document.createElement('a')
      link.href = url
      link.download = fileName
      link.style.display = 'none'
      document.body.appendChild(link)
      // 触发点击
      link.click()
      // 清理
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    }).catch((error) => {
      console.error('下载Excel文件时发生错误:', error)
    })
  }
}

